package Java9_23;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

public class Product5 {
    public static void add(boolean dis,String ip,int it,String name,double price,int st,String unit){
        SAXReader reader=new SAXReader();
        Document doc=null;
        try {
            doc=reader.read(new File("D:\\IdeaProjects\\src\\Java9_23\\products.xml"));
            List<Element> list = doc.selectNodes("/shop/product[name=" + name + "]");
            List<Element> list1 = doc.selectNodes("/shop/product[itemno=" + it + "]");
            if(list.size()==0&&list1.size()==0){
                Element element=doc.getRootElement();
                Element e=element.addElement("product");

                e.addAttribute("discount",String.valueOf(dis));
                e.addAttribute("factoryaddr",ip);

                Element ename=e.addElement("name");
                ename.setText(name);
                Element eitem=e.addElement("itemno");
                eitem.setText(String.valueOf(it));
                Element eprice=e.addElement("price");
                eprice.setText(String.valueOf(price));
                Element ecount=e.addElement("stockcount");
                ecount.setText(String.valueOf(st));
                Element eunit=e.addElement("unit");
                eunit.setText(unit);

                OutputFormat format = OutputFormat.createPrettyPrint();
                format.setEncoding("utf-8");
                XMLWriter xw=new XMLWriter(new FileOutputStream("D:\\IdeaProjects\\src\\Java9_23\\products.xml"),format);
                xw.write(doc);
                System.out.println("成功打印");
                xw.close();
            }else {
                System.out.println("商品号或商品名称重复");
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        add(true,"安徽",2900,"六神",9.9,999,"瓶");
    }
}
